<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>创建用户
            </el-button>
            <el-button type="success" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="userList" 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="warning" size="small" @click="handleResetPassword(row)">
                <el-icon><Key /></el-icon>
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无用户数据" />
        </template>
      </el-table>
      
      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchUserList"
          @current-change="fetchUserList"
        />
      </div>
    </el-card>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '创建用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item 
          label="密码" 
          prop="password"
          v-if="dialogType === 'create'"
        >
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="重置密码"
      width="30%"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  Plus,
  Refresh,
  Edit,
  Delete,
  Key
} from '@element-plus/icons-vue'

const dialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref(null)
const passwordFormRef = ref(null)

const form = reactive({
  username: '',
  password: '',
  status: 1
})

const passwordForm = reactive({
  password: '',
  confirmPassword: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户列表数据
const userList = ref([])

// 添加loading状态
const loading = ref(false)

// API 方法
const api = {
  // 获取用户列表
  getUserList: async (current, size) => {
    try {
      const response = await axios.get(`/api/user/list`, {
        params: { current, size }
      })
      return response.data
    } catch (error) {
      console.error('获取用户列表失败:', error)
      throw error
    }
  },

  // 添加或更新用户
  saveUser: async (user) => {
    try {
      const response = await axios.post('/api/user/add', user)
      return response.data
    } catch (error) {
      console.error('保存用户失败:', error)
      throw error
    }
  },

  // 删除用户
  deleteUser: async (id) => {
    try {
      const response = await axios.delete(`/api/user${id}/delete`)
      return response.data
    } catch (error) {
      console.error('删除用户失败:', error)
      throw error
    }
  }
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const result = await api.getUserList(pagination.current, pagination.size)
    if (result.code === '200') {
      userList.value = result.data.data || []
      pagination.total = result.data.total || 0
    } else if (result.code !== '200' && result.message) {
      // 只有在非成功状态且有错误消息时才显示错误提示
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})

const handleCreate = () => {
  dialogType.value = 'create'
  dialogVisible.value = true
  form.username = ''
  form.password = ''
  form.status = 1
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, row)
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await api.deleteUser(row.id)
      if (result.code === '200') {
        ElMessage.success(result.message || '删除成功')
        fetchUserList()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleResetPassword = (row) => {
  passwordDialogVisible.value = true
  passwordForm.password = ''
  passwordForm.confirmPassword = ''
}

const handleRefresh = () => {
  fetchUserList()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // 创建用户时不传id
    const submitData = dialogType.value === 'create' 
      ? { username: form.username, password: form.password, status: form.status }
      : form
    const result = await api.saveUser(submitData)
    if (result.code === '200') {
      dialogVisible.value = false
      ElMessage.success(result.message || (dialogType.value === 'create' ? '创建成功' : '修改成功'))
      fetchUserList()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('操作失败')
  }
}

const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    // 创建表单数据
    const params = new URLSearchParams()
    params.append('username', JSON.parse(localStorage.getItem('user')).username)
    params.append('password', passwordForm.password)
    params.append('surePassword', passwordForm.password)

    const response = await axios.post('/api/user/updatePassword', params)
    
    if (response.data.code === '200') {  // 使用字符串形式比较
      passwordDialogVisible.value = false
      ElMessage({
        message: '密码重置成功',
        type: 'success'
      })
      // 重置表单
      passwordForm.password = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage({
        message: response.data.message || '密码重置失败',
        type: 'error'
      })
    }
  } catch (error) {
    if (error.name === 'SyntaxError') {
      ElMessage({
        message: '获取用户信息失败',
        type: 'error'
      })
    } else if (error.response?.status === 429) {
      ElMessage({
        message: '操作太频繁，请稍后再试',
        type: 'warning'
      })
    } else {
      ElMessage({
        message: error.response?.data?.message || '密码重置失败',
        type: 'error'
      })
    }
    console.error('密码重置失败:', error)
  }
}
</script>

<style scoped>
.users-container {
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-actions {
  display: flex;
  gap: 12px;
}

:deep(.el-card) {
  width: 100%;
  height: 100%;
}

:deep(.el-table) {
  width: 100% !important;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 